# encoding: UTF-8

IN_FILE = 'data.raw'
OUTPUT_FILE = 'ztree.province.city.js'

class Tree
  attr_accessor :name, :code, :children, :parent, :parent_code

  def initialize(name, code, level)
    code = code.to_i
    level = level.to_i
    @name = name
    @code = code
    @children = []
    @parent = nil
    @parent_code = code / 100**(5 - level) * 100**(5 - level)
  end

  def parent=(parent)
    @parent = parent
    parent.children << self
  end

  def write(out)
    out.write(',') if parent and parent.children.size > 0 and parent.children[0].code != @code
    out.write("{name:'#@name',code:#@code")
    if children.size > 0
      out.write(',children:[')
      children.each { |child| child.write(out) }
      out.write(']')
    end
    out.write("}")
  end
end

root = Tree.new("全部", 0, 0)
nodes = {}
File.open(IN_FILE, 'r') do |in_file|
  while (line = in_file.gets)
    arr = line.chomp.split("\t")
    node = Tree.new(arr[2], arr[1], arr[0])
    nodes[node.code] = node
  end
end
nodes.each_value { |e| e.parent = nodes[e.parent_code] || root }
File.open(OUTPUT_FILE, 'w') do |out_file|
  out_file.write("var ztree_province_city=[")
  root.write(out_file)
  out_file.write("];")
end
